<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Admin\Controller\AdminController;
use Admin\Service\ApiService;

/**
 * 模型数据管理控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class ProductController extends ThinkController {

	private $model_id = 6;

    /**
     * 显示指定模型列表数据
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     * @param null $model
     * @param int $p
     */
    public function lists($model = null, $p = 0){

        $this->assign('active_menu','product/lists');
        parent::lists('product',$p,['status'=>['gt',-1]]);
    }

    public function edit($model = null, $id = 0){
    	$model = $this->model_id;
        //获取模型信息
        $model = M('Model')->find($model);
        $model || $this->error('模型不存在！');

        if(IS_POST){
        	$Model  =   D('Product');
            // 获取模型的字段信息
            $Model  =   $this->checkAttr($Model,$model['id']);
            if($Model->create() && $Model->save()){
            	//删除旧的图片，并添加新的
            	M('Product_picture')->where('product_id='.$id)->delete();
            	$this->_add_pic($id);

                //清空前台缓存
                $api = new ApiService();
                $api->setApiUrl(C('APIURI.mall'))
                    ->setData()->send('index/console/cleanCache');

                $this->success('保存'.$model['title'].'成功！', U('lists?model='.$model['name']));
            } else {
                $this->error($Model->getError());
            }
        } else {
            //获取数据
            $data       = M(get_table_name($model['id']))->find($id);
            $data || $this->error('数据不存在！');
            
            $data['market_price'] = $data['market_price']/100; //单位转成分
            $data['price'] = $data['price']/100; //单位转成分
            $data['earning'] = $data['earning']/1000; //单位转成厘

            $pics = M('Product_picture')->where(array('product_id'=>$data['id']))->getField('sort,picture_id',TRUE);
            foreach ($pics as $k=>$pic){
            	$data['pic'.$k] = $pic;
            }
//             print_r($data);die;
            $this->assign('model', $model);
            $this->assign('fields', $this->_get_fields());
            $this->assign('data', $data);
            $this->meta_title = '编辑'.$model['title'];
            $this->display($model['template_edit']?$model['template_edit']:'');
        }
    }

    public function add($model = null){
        //获取模型信息
        $model = M('Model')->where(array('status' => 1))->find($this->model_id);
        $model || $this->error('模型不存在！');
        if(IS_POST){
        	$Model  =   D('Product');
        	// 获取模型的字段信息
        	$Model  =   $this->checkAttr($Model,$model['id']);
        	if($Model->create() && $id=$Model->add()){
            	$this->_add_pic($id);
                //清空前台缓存
                $api = new ApiService();
                $api->setApiUrl(C('APIURI.mall'))
                    ->setData()->send('index/console/cleanCache');
        		$this->success('添加'.$model['title'].'成功！', U('lists?model='.$model['name']));
        	} else {
        		$this->error($Model->getError());
        	}
        } else {
			
        	
        	$this->assign('model', $model);
        	$this->assign('fields', $this->_get_fields());
        	$this->meta_title = '新增'.$model['title'];
        	$this->display($model['template_add']?$model['template_add']:'');
        }
    }
    

    /**
     * 回收站列表
     * @author wangxuebing <406964108@qq.com>
     */
    public function recycle(){
    	
    	$map['status']  =   -1;
    	$list = AdminController::lists(M('Product'),$map,'update_time desc');
    	//处理列表数据
    	
    	$this->assign('list', $list);
    	$this->meta_title       =   '回收站';
    	$this->display();
    }

    /**
     * 还原被删除的数据
     * @author huajie <banhuajie@163.com>
     */
    public function permit(){
    	/*参数过滤*/
    	$ids = I('param.ids');
    	if(empty($ids)){
    		$this->error('请选择要操作的数据');
    	}
    
    	/*拼接参数并修改状态*/
    	$Model  =   'Product';
    	$map    =   array();
    	if(is_array($ids)){
    		$map['id'] = array('in', $ids);
    	}elseif (is_numeric($ids)){
    		$map['id'] = $ids;
    	}
    	$this->restore($Model,$map);
    }
    

    /**
     * 清空回收站
     * @author huajie <banhuajie@163.com>
     */
    public function clear(){
    	$res = M('Product')->where(array('status'=>'-1'))->delete();
    	if($res !== false){
    		$this->success('清空回收站成功！');
    	}else{
    		$this->error('清空回收站失败！');
    	}
    }
    
    private function _level_title($item){
    	$space = '';
    	for($i=1;$i<$item['level'];$i++){
    		$space .= '- - ';
    	}
    	$space = empty($space) ? '' : '|'.$space;
    	
    	$item['title'] = $space.$item['title'];
    	return $item;
    }
    /**
     * 
     * @param string $data
     * @return Ambigous <multitype:string number , string, mixed, multitype:multitype: , multitype:unknown >
     */
    private function _get_fields(){

    	$fields = get_model_attribute($this->model_id);

    	for($i=0;$i<5;$i++){
    		$img_field = array(
    				'id'=>'',
    				'name'=>'pic'.$i,
    				'title'=>'图片'.($i+1),
    				'type'=>'picture',
    				'value'=>'',
    				'remark'=>'',
    				'is_show'=>1,
    				'extra'=>"160,160\r\n55,40\r\n770,432",
    				'model_id'=>'',
    				'is_must'=>'',
    				'status'=>'',
    		);
    		$fields[2][] = $img_field;
    	}
    	ksort($fields);
//     	print_r($fields[2]);die;
    	
    	return $fields;
    }
    
    private function _add_pic($product_id){
    	$pics = array();
    	for($i=0;$i<5;$i++){
    		$pic = I('post.pic'.$i);
    		if($pic){
	    		$pics[] = array('product_id'=>$product_id,'picture_id'=>$pic,'sort'=>$i);
    		}
    	}
    	if($pics){
    		M('Product_picture')->addAll($pics);
    	}
    }
}